﻿using System;
using System.Configuration;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Shuba.Business;

namespace Shuba.Web.bulk_upload
{
    public partial class branch_rollout_mobile_version_add : basePage
    {
        bool IsAdd = false;
        string msg = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            string acl = GetUserAccess("MSTR_BRANCH_ROLLOUT_MOBILE");

            IsAdd = IsUserAdd(acl);

            if (!IsAdd)
            {
                msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                InitRegionList();
                InitClusterList(ddlRegion.SelectedValue);
                initVersion();

                txtImplDate.Text = DateTime.Today.ToString("dd MMMM yyyy");
                LabelTitle.Text = GetPageTitle("MSTR_BRANCH_ROLLOUT_MOBILE");
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void BindData()
        {
            string RegionID = ddlRegion.SelectedValue;
            string ClusterID = ddlCluster.SelectedValue;

            var bl = new Branch();

            if (RegionID == "ALL") RegionID = "%";
            if (ClusterID == "ALL") ClusterID = "%";
            
            gvList.DataSource = bl.GetListByRegionAndCluster(RegionID, ClusterID);
            gvList.DataBind();

            branch_rollout_mobile_version blr = new branch_rollout_mobile_version();
            var branchRollout = new List<Shuba.Model.branch_rollout_versionInfo>();
            branchRollout = blr.getBranchRollout(RegionID, ClusterID, ddlVersion.SelectedValue);

            hidIndex.Value = "true";
            foreach (GridViewRow row in gvList.Rows)
            {
                string brchID = gvList.DataKeys[row.RowIndex].Values["BranchID"].ToString();
                foreach (Shuba.Model.branch_rollout_versionInfo brc in branchRollout)
                {
                    if (brchID == brc.BranchID)
                    {
                        CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");
                        //chkItemSelect.Checked = true;

                        row.Cells[3].Text = brc.implementation_date.ToString("dd MMMM yyyy");
                        row.Font.Bold = true;
                        row.ForeColor = System.Drawing.Color.DarkGreen;

                        if (brc.implementation_date.Date != Convert.ToDateTime(txtImplDate.Text).Date) hidIndex.Value = "false";
                    }
                }
            }

            if (gvList.Rows.Count > 0)
            {
                btnSubmit.Visible = true;
                btnCancel.Visible = true;
            }
            else
            {
                btnSubmit.Visible = false;
                btnCancel.Visible = false;
            }
        }

        private void InitRegionList()
        {
            var _Region = new Shuba.Business.Regional();

            ddlRegion.DataTextField = "RegionalName";
            ddlRegion.DataValueField = "RegionalID";
            ddlRegion.DataSource = _Region.GetAll();
            ddlRegion.DataBind();

            if (ddlRegion.Items.Count > 1)
            {
                ListItem ListAll = new ListItem();
                ListAll.Value = "ALL";
                ListAll.Text = " = ALL REGION = ";

                ddlRegion.Items.Insert(0, ListAll);
            }
        }

        protected void ddlRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitClusterList(ddlRegion.SelectedValue);
        }

        private void InitClusterList(string RegionalID)
        {
            var _Cluster = new Shuba.Business.Cluster();

            if (RegionalID == "ALL") RegionalID = "%";

            ddlCluster.DataTextField = "ClusterName";
            ddlCluster.DataValueField = "ClusterID";
            ddlCluster.DataSource = _Cluster.GetListByRegion(RegionalID);
            ddlCluster.DataBind();

            if (ddlCluster.Items.Count > 1)
            {
                ListItem ListAll = new ListItem();
                ListAll.Value = "ALL";
                ListAll.Text = " = ALL CLUSTER = ";
                ddlCluster.Items.Insert(0, ListAll);
            }
        }

        private void initVersion()
        {
            var bsRollout = new branch_rollout_mobile_version();
            ddlVersion.Items.Clear();
            ddlVersion.Items.Add(new ListItem("- SELECT -", ""));

            List<string> list = bsRollout.getVersion();
            foreach (string info in list)
            {
                ddlVersion.Items.Add(new ListItem(info, info));
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            var bsRoll = new Shuba.Business.branch_rollout_mobile_version();
            var info = new Shuba.Model.branch_rollout_versionInfo();

            string ActType = "";
            int ErrorCount = 0, SuccessCount = 0;
            DateTime implDate = Convert.ToDateTime(txtImplDate.Text);

            string RegionID = ddlRegion.SelectedValue;
            string ClusterID = ddlCluster.SelectedValue;

            if (RegionID == "ALL") RegionID = "%";
            if (ClusterID == "ALL") ClusterID = "%";
            var branchRollout = new List<Shuba.Model.branch_rollout_versionInfo>();
            branchRollout = bsRoll.getBranchRollout(RegionID, ClusterID, ddlVersion.SelectedValue);

            /*
            hidIndex.Value = "true";
            foreach (GridViewRow row in gvList.Rows)
            {
                string brchID = gvList.DataKeys[row.RowIndex].Values["BranchID"].ToString();
                foreach (Shuba.Model.branch_rollout_versionInfo brc in branchRollout)
                {
                    if (brchID == brc.BranchID)
                    {
                        if (brc.implementation_date.Date != Convert.ToDateTime(txtImplDate.Text).Date)
                        {
                            hidIndex.Value = "false";
                            break;
                        }
                    }
                }
            }
            */

            bool isExistPending = false;

            if (implDate.Date < ProcessingDate().Date)
            {
                Alert("Implementation Date harus lebih besar dari tanggal sekarang");
            }
            else if (ddlVersion.SelectedValue == "")
            {
                Alert("Silakan pilih version");
            }
            else
            {
                foreach (GridViewRow row in gvList.Rows)
                {
                    CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                    if (chkItemSelect.Checked)
                    {
                        string branchID = gvList.DataKeys[row.RowIndex].Value.ToString();

                        if (bsRoll.IsPending(branchID, ddlVersion.SelectedValue))
                        {
                            isExistPending = true;
                        }

                        if (Request.QueryString["a"] != "ed")
                        {
                            info = bsRoll.Get(branchID, ddlVersion.SelectedValue);
                            if (info.BranchID == null && info.version == null)
                            {
                                ActType = "INSERT";
                            }
                            else
                            {
                                ActType = "UPDATE";
                            }
                        }
                        else
                        {
                            ActType = "UPDATE";
                        }

                        if (!bsRoll.IsPending(branchID, ddlVersion.SelectedValue))
                        {
                            info.BranchID = branchID;
                            info.version = ddlVersion.SelectedValue;
                            info.implementation_date = Convert.ToDateTime(txtImplDate.Text);
                            info.is_delete = "0";
                            info.entry_by = HttpContext.Current.User.Identity.Name;
                            info.entry_date = ProcessingDate();
                            info.update_by = HttpContext.Current.User.Identity.Name;
                            info.update_date = ProcessingDate();
                            info.ActType = ActType;
                            try
                            {
                                if (bsRoll.Save(info) > 0)
                                {
                                    SuccessCount++;
                                    AddLog(ActType, ActType + " BRANCH ROLLOUT MOBILE VERSION");
                                }
                                else
                                {
                                    ErrorCount++;
                                }
                            }
                            catch (Exception ex)
                            {
                                ErrBox.Visible = true;
                                ErrMsg.Text = ex.Message;
                            }
                        }
                    }
                }
                if (SuccessCount > 0 || ErrorCount > 0)
                {
                    if (isExistPending)
                    {
                        msg = "Save Notification\\n\\nSuccessfully Save : " + SuccessCount + " Record(s)\\n\\nFailed to Save : " + ErrorCount + " Record(s)\\n\\nSome data already pending approve";
                    }
                    else
                    {
                        msg = "Save Notification\\n\\nSuccessfully Save : " + SuccessCount + " Record(s)\\n\\nFailed to Save : " + ErrorCount + " Record(s)";
                    }
                    AlertAndRedirect(msg, "branch_rollout_mobile_version_list.aspx");
                }
                if (SuccessCount == 0 && isExistPending)
                {
                    msg = "Some data already pending approve\\nPlease approve first or change selected data";
                    Alert(msg);
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("branch_rollout_mobile_version_list.aspx");
        }

        protected void gvList_SelectedIndexChanged(object sender, EventArgs e)
        {
            hidIndex.Value = gvList.SelectedIndex.ToString();
        }

        protected void gvList_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            hidIndex.Value = gvList.SelectedIndex.ToString();
        }

        protected void gvList_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
                e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
                e.Row.ToolTip = "Click to select row";
                e.Row.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this.gvList, "Select$" + e.Row.RowIndex);
            }
        }
    }
}